<?php
	$form = $_POST;
	$tour = new Tour();
	$tour->setname($form['tour_name']);
	$tour->setstart_date($form['start_date']);
	$tour->setend_date($form['end_date']);
	$tour->setnumber_day($form['number_day']);
	$tour->setnumber_night($form['number_night']);
	$tour->setprice($form['price']);
	$tour->setpromotion($form['promotion']);
	$tour->setcurrency($form['currency']);
	$tour->setoverview($form['overview']);
	$tour->setdescription($form['description']);
	
	$tour_category = new TourCategory();
	if ($tour_id)
	{
		$tour_old = new Tour();
		$tour_old->select($tour_id);
		$categories_old = $tour_old->getAllTourCategories();
		foreach($categories_old as $category_old)
			$tour_category->delete($category_old->getid());
	}
	
	$prefixes = array();
	$prefixes[] = 'tour_price_';
	$prefixes[] = 'tour_ideas_';
	$prefixes[] = 'tour_ads_';
	$pic_id = check_and_upload_picture('thumbnail', $form['thumbnail_name'], $HTTP_POST_FILES, $prefixes);
	if ($pic_id) {
		// TODO: remove the old one
		if (isset($tour_id)) {
			$tour->select($tour_id);
			$old_pic_id = $tour->getthm_picture();
			$tour->setthm_picture($pic_id);
			$tour->update();
			if ($old_pic_id) {
				$old_pic = new Picture();
				$old_pic->select($old_pic_id);
				$old_pic->deleteAllFiles();
				$old_pic->delete();
			}
		}
		$tour->setthm_picture($pic_id);
	} elseif ($tour_id) {
		$tmp_tour = new Tour();
		$tmp_tour->select($tour_id);
		$tour->setthm_picture($tmp_tour->getthm_picture());
	}
	
	$pic_id = check_and_upload_picture('ads_picture', $form['ads_picture_name'], $HTTP_POST_FILES ,$prefixes);
	if ($pic_id) {
		// TODO: remove the old one
		if (isset($tour_id)) {
			$tour->select($tour_id);
			$old_pic_id = $tour->getads_picture();
			$tour->setads_picture($pic_id);
			$tour->update();
			if ($old_pic_id) {
				$old_pic = new Picture();
				$old_pic->select($old_pic_id);
				$old_pic->deleteAllFiles();
				$old_pic->delete();
			}
		}
		$tour->setads_picture($pic_id);
	} elseif ($tour_id) {
		$tmp_tour = new Tour();
		$tmp_tour->select($tour_id);
		$tour->setads_picture($tmp_tour->getads_picture());
	}
	
	$tour->setactive($form['active'] == 'on' ? 1 : 0);
	if ($tour_id) { // it's an update action
		$tour->update($tour_id);
		$tour->select($tour_id);
	} else { // it's an create action
		$tour->insert();
	}

	$categories = explode(',',$form['categories']);
	foreach ($categories as $category_id)
	{
		if ($category_id != '')
		{
			$tour_category->settour_id($tour->getid());
			$tour_category->setcategory_id($category_id);
			$tour_category->insert();
		}
	}

	$msg = $tour_id ? "Tour đã được sửa thành công" : "Tour đã được thêm thành công";
	admin_load($msg, "?act=tours_manager");
?>